/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package br.com.deployment.utilitario;

import br.com.deployment.enums.Relatorio;
import java.io.IOException;
import java.io.InputStream;
import java.util.Collection;
import java.util.HashMap;
import javax.faces.context.FacesContext;
import javax.servlet.ServletContext;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import net.sf.jasperreports.engine.*;
import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource;
import net.sf.jasperreports.engine.fill.JRAbstractLRUVirtualizer;
import net.sf.jasperreports.engine.fill.JRSwapFileVirtualizer;
import net.sf.jasperreports.engine.util.JRSwapFile;

/**
 *
 * @author roniere
 */
public class GeraRelatorio {
    
    
    
     public static void relatorio(HashMap<String, Object> parametros, Collection<?> collection , Relatorio relatorio){
        try{
            
            JRSwapFile file = new JRSwapFile("/tmp", 4096, 10);
            
            JRAbstractLRUVirtualizer virtualizer = new JRSwapFileVirtualizer(10, file, true);
            
            parametros.put(JRParameter.REPORT_VIRTUALIZER, virtualizer);
            
            
            
            FacesContext facesContext = FacesContext.getCurrentInstance();
            ServletContext servletContext = (ServletContext) facesContext.getExternalContext().getContext();            
            
            InputStream stream = Thread.currentThread().getContextClassLoader().getResourceAsStream(relatorio.getUrl());
            
            HttpServletResponse response = (HttpServletResponse) facesContext.getExternalContext().getResponse();
     
        
            ServletOutputStream ouputStream = response.getOutputStream();
            
            JRDataSource jrds;
            if(collection != null){
                jrds = new JRBeanCollectionDataSource( collection );
            }else{
                jrds = new JREmptyDataSource();
            }
            
            JasperRunManager.runReportToPdfStream(stream, ouputStream, parametros, jrds);
            
            response.setHeader("Content-Disposition", "inline; filename=\"relatorio.pdf\""); 
            response.setContentType("application/pdf");
            facesContext.responseComplete();
            ouputStream.flush();
            ouputStream.close();
            
        } catch (IOException ex) {
            Msg.messagemError("Erro ao gerar relatório IOEX");
            
        } catch (JRException ex) {
            System.err.println(ex);
            Msg.messagemError("Erro ao gerar relatório JREX");
        }
        
    
    }
    
    
}
